﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace ResourceManager
{

    enum ResourceStatus
    {
        None,
        Prepare,
        Loading,
        Loaded
    }

    /// <summary>
    /// 资源集合，用于控制资源状态等
    /// </summary>
    class ResourceCollection
    {
        public ResourceCollection()
        {
            _dict = new Dictionary<string, ResourceInfo>();
            _list = new List<string>();
        }

        public ResourceStatus this[string name]
        {
            get
            {
                try
                {
                    return _dict[name].status;
                }
                catch (System.Exception)
                {
                    return ResourceStatus.None;
                }
            }
            set
            {
                ResourceInfo info = _dict[name];
                info.status = value;
                _dict[name] = info;
            }
        }

        public void Add(string resourceName, ResourceStatus status, object userState)
        {
            lock (((ICollection)_dict).SyncRoot)
            {
                ResourceInfo info;
                info.status = status;
                info.userState = userState;
                _dict[resourceName] = info;
            }
        }

        public void Remove(string name)
        {
            lock (((ICollection)_dict).SyncRoot)
            {
                if (_dict.Remove(name))
                {
                    _list.Add(name);
                }
            }
        }

        public bool Random(string excludeName, out string name, out object userState)
        {
            name = default(string);
            userState = default(object);

            foreach (KeyValuePair<string, ResourceInfo> item in _dict)
            {
                if (item.Key != excludeName)
                {
                    name = item.Key;
                    userState = item.Value.userState;
                    return true;
                }
            }
            return false;
        }

        public int LoadingCount
        {
            get
            {
                lock (((ICollection)_dict).SyncRoot)
                {
                    int count = 0;
                    foreach (ResourceInfo info in _dict.Values)
                    {
                        if (info.status == ResourceStatus.Loading)
                        {
                            count++;
                        }
                    }
                    return count;
                }
            }
        }

        public struct ResourceInfo
        {
            public ResourceStatus status;
            public object userState;
        }

        Dictionary<string, ResourceInfo> _dict;

        List<string> _list;
    }  
}
